package com.sdx.console.meetProduct.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.util.ValidateConfig;
import com.ibeetl.admin.core.web.AuthorizedBaesController;
import com.ibeetl.admin.core.web.JsonResult;
import com.sdx.common.utils.JacksonUtils;
import com.sdx.common.utils.Utils;
import com.sdx.console.customer.entity.CustomerInfo;
import com.sdx.console.meetProduct.entity.MeetProduct;
import com.sdx.console.meetProduct.entity.MeetProductCust;
import com.sdx.console.meetProduct.service.MeetProductService;
import org.apache.commons.lang3.StringUtils;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.db.KeyHolder;
import org.beetl.sql.core.engine.PageQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * 一对一服务 接口
 */
@RequestMapping("/meetProduct/meetProduct")
@Controller
public class MeetProductController extends AuthorizedBaesController{
	private static final Logger log = LoggerFactory.getLogger(MeetProductController.class);
    private static final String MODEL = "/meetProduct/meetProduct";

    @Resource
	private MeetProductService meetProductService;

	/**
	 * 初始化页面需要的列表数据，
	 *
	 */
	private void setPageParam(ModelAndView view,HttpServletRequest request) {

	}

    /* 页面 */

    @GetMapping("/index.do")
    @Function("meetProduct.meetProduct.query")
    @ResponseBody
    public ModelAndView index(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/index.html") ;
		setPageParam(view,request);
        return view;
    }

    @GetMapping("/edit.do")
    @Function("meetProduct.meetProduct.edit")
    @ResponseBody
    public ModelAndView edit(HttpServletRequest request,Integer productId) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        MeetProduct meetProduct = meetProductService.queryById(productId);
        List<String> list = meetProductService.queryCustByProductId(productId);
        meetProduct.setCustomerIds("'"+StringUtils.join(list, "','")+"'");
        view.addObject("meetProduct", meetProduct);
		setPageParam(view,request);
		try {
			view.addObject("meetProductJson", JacksonUtils.toJsonString(meetProduct,JacksonUtils.DF1));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
        return view;
    }

    @GetMapping("/add.do")
    @Function("meetProduct.meetProduct.add")
    @ResponseBody
    public ModelAndView add(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
		setPageParam(view,request);
        return view;
    }

    /* ajax json */

    @PostMapping("/list.json")
    @Function("meetProduct.meetProduct.query")
    @ResponseBody
    public JsonResult<PageQuery> list(MeetProduct condtion)
    {
        PageQuery page = condtion.getPageQuery();
        meetProductService.queryByCondition(page);
        return JsonResult.success(page);
    }

    private JsonResult save(boolean isNew,MeetProduct meetProduct,HttpServletRequest request
	) {
    	JsonResult result = JsonResult.success();
		CoreUser user = getLoginUser(request);

    	if (isNew) {
            meetProduct.setCreatedBy(user.getId().intValue());
            meetProduct.setCreatedName(user.getName());
			meetProduct.setCreatedTime(new Date());
            KeyHolder keyHolder = new KeyHolder();
            meetProductService.getSqlManager().insertTemplate(MeetProduct.class,meetProduct,keyHolder);
            Integer key = keyHolder.getInt();
            if(StringUtils.isNotEmpty(meetProduct.getCustomerIds())){
                List<String> idList = Utils.strToList(meetProduct.getCustomerIds(),",");
                List<MeetProductCust> meetProductCusts = new ArrayList<>();
                for (String custId : idList) {
                    MeetProductCust cust = new MeetProductCust();
                    cust.setCustomerId(custId);
                    cust.setProductId(key);
                    meetProductCusts.add(cust);
                }
                meetProductService.getSqlManager().insertBatch(MeetProductCust.class,meetProductCusts);
            }

		} else {
			meetProduct.setUpdatedTime(new Date());
            meetProduct.setUpdatedBy(user.getId().intValue());
            meetProduct.setUpdatedName(user.getName());
			meetProductService.updateTemplate(meetProduct);
			List<String> ids = new ArrayList<>();
            ids.add(meetProduct.getProductId().toString());
            meetProductService.delMeetCust(ids);
            if(StringUtils.isNotEmpty(meetProduct.getCustomerIds())){
                List<String> idList = Utils.strToList(meetProduct.getCustomerIds(),",");
                List<MeetProductCust> meetProductCusts = new ArrayList<>();
                for (String custId : idList) {
                    MeetProductCust productCust = new MeetProductCust();
                    productCust.setCustomerId(custId);
                    productCust.setProductId(meetProduct.getProductId());
                    meetProductCusts.add(productCust);
                }
                meetProductService.getSqlManager().insertBatch(MeetProductCust.class,meetProductCusts);
            }
		}
		return result;
	}
    @PostMapping("/add.json")
    @Function("meetProduct.meetProduct.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)MeetProduct meetProduct,HttpServletRequest request)
    {

        return save(true,meetProduct,request);
    }

    @PostMapping("/update.json")
    @Function("meetProduct.meetProduct.edit")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  MeetProduct meetProduct,HttpServletRequest request) {
		return save(false,meetProduct,request);
    }



    @GetMapping("/view.json")
    @Function("meetProduct.meetProduct.query")
    @ResponseBody
    public JsonResult<MeetProduct>queryInfo(Integer productId) {
        MeetProduct meetProduct = meetProductService.queryById( productId);
        return  JsonResult.success(meetProduct);
    }

    @PostMapping("/delete.json")
    @Function("meetProduct.meetProduct.del")
    @ResponseBody
    public JsonResult delete(String ids) {
		List<String> idList = Utils.strToList(ids,",");
        meetProductService.batchDelMeetProduct(idList);
        return JsonResult.success();
    }


    @PostMapping("/getCust.json")
    @ResponseBody
    public List<CustomerInfo> getCust() {
        CustomerInfo customerInfo = new CustomerInfo();
        customerInfo.setIsTeacher(1);
        customerInfo.setCustStatus(1);
        List<CustomerInfo> list = meetProductService.getSqlManager().template(customerInfo);
        return list;
    }


}
